import { DialogService } from './../../../dialog.service';
import { CrisisService } from './../crisis.service';
import { Crisis } from './../crisis';

import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute, ParamMap, Router } from '@angular/router';
import { Location } from '@angular/common';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-hero-detail',
  templateUrl: './crisis-detail.component.html',
  styleUrls: ['./crisis-detail.component.css']
})
export class CrisisDetailComponent implements OnInit {

  // 这个当作初始值
  crisis!: Crisis
  // 使用editName是为了 后面确认框要用到，判断值是否变化
  editCrisis!: Crisis

  constructor(

     private activedRoute: ActivatedRoute,
     private crisisService: CrisisService,
     private router: Router,

     public dialogService: DialogService

  ) { }

  getCrisis(): void{
     const id = Number(this.activedRoute.snapshot.paramMap.get('id'))
     this.crisisService.getCrisis(id).subscribe(
      crisis => {
        this.crisis = crisis
        this.editCrisis = crisis
      }
     )
  }

  ngOnInit(): void {

    this.getCrisis()
  }

  goBack() {
    const crisisId = this.crisis ? this.crisis.id : null;
    // Pass along the crisis id if available
    // so that the CrisisListComponent can select that crisis.
    // Add a totally useless `foo` parameter for kicks.
    // Relative navigation back to the crises
    this.router.navigate(['../', { id: crisisId, foo: 'foo' }], { relativeTo: this.activedRoute });
  }

  save(): void{

    this.crisisService.updateCrisis(this.editCrisis).subscribe(() => this.goBack())

  }

  canDeactivate(): Observable<boolean> | boolean {
    // Allow synchronous navigation (`true`) if no crisis or the crisis is unchanged
    if (!this.crisis || this.crisis.name === this.editCrisis.name) {
      return true;
    }
    // Otherwise ask the user with the dialog service and return its
    // observable which resolves to true or false when the user decides
    return this.dialogService.confirm('Discard changes?');
  }

}
